package edu.gdpu.memory.direct;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.stream.Stream;

/**
 * @author mazebin
 * @date 2021年 07月15日 14:32:59
 * 演示直接内存
 * ByteBuffer
 */
public class DirectMemoryTest1 {
    static final String FROM = "D:\\LanqiaoJavaA\\Java语言A组\\1\\题目.txt";
    static final String TO = "D:\\LanqiaoJavaA\\Java语言A组\\2\\题目1.txt";
    static final int _1Mb = 1024 * 1024;

    public static void main(String[] args) {
        //io();//io用时：106.3047
        directBuffer();//directBuffer用时：5.3376
    }

    private static void directBuffer() {
        long start =System.nanoTime();//这个函数经常用来计算一段代码的执行时间
        // ，获取数据库链接的所用时间，网络访问时间
        try(
                FileChannel from = new FileInputStream(FROM).getChannel();
                FileChannel to = new FileOutputStream(TO).getChannel();

                ){
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_1Mb);
            while(true){
                int len = from.read(byteBuffer);
                if(len == -1){
                    break;
                }
                byteBuffer.flip();
                to.write(byteBuffer);
                byteBuffer.clear();
            }

        }catch ( Exception  e){
            e.printStackTrace();
        }
        long end =System.nanoTime();
        System.out.println("directBuffer用时："+(end-start)/ 1000_000.0);

    }

    private static void io() {
        long start = System.nanoTime();
        try(FileInputStream from = new FileInputStream(FROM);
            FileOutputStream to = new FileOutputStream(TO);
                ){
       byte[] bytes =  new byte[_1Mb];
       while(true){
           int len = from.read(bytes);
           if(len ==-1){
               break;
           }
           to.write(bytes,0,len);
       }
        }catch ( Exception e ){
            e.printStackTrace();
        }
        long end =System.nanoTime();
        System.out.println("io用时："+(end-start)/ 1000_000.0);
    }
}
